<template>
  <div class="health-report-container">
    <!-- 返回上一页按钮 -->
    <div class="back-button" @click="goBack">
      <i class="el-icon-back"></i>
      <span>返回</span>
    </div>

    <!-- 页面标题 -->
    <div class="report-header">
      <h1>{{ headTitle }}</h1>
      <p class="report-date">{{ formatReportDate(reportData.createTime) }}</p>
    </div>

    <!-- 健康数据概览 -->
    <div class="health-summary">
      <div class="summary-card">
        <div class="summary-icon">🚶‍♂️</div>
        <div class="summary-content">
          <h3>今日步数</h3>
          <p class="summary-value">{{ reportData.stepNumber || '--' }} 步</p>
          <div class="trend-indicator" :class="getStepTrendClass()">
            {{ getStepTrendText() }}
          </div>
        </div>
      </div>

      <div class="summary-card">
        <div class="summary-icon">💧</div>
        <div class="summary-content">
          <h3>饮水量</h3>
          <p class="summary-value">{{ reportData.waterVolume || '--' }}L</p>
          <div class="trend-indicator" :class="getWaterTrendClass()">
            {{ getWaterTrendText() }}
          </div>
        </div>
      </div>

      <div class="summary-card">
        <div class="summary-icon">🛌</div>
        <div class="summary-content">
          <h3>睡眠时长</h3>
          <p class="summary-value">{{ calculateSleepDuration() }}</p>
          <div class="trend-indicator" :class="getSleepTrendClass()">
            {{ getSleepTrendText() }}
          </div>
        </div>
      </div>
    </div>

    <!-- 图表展示区域 -->
    <div class="charts-container">
      <!-- 步数趋势图 -->
      <div class="chart-card">
        <h3>步数趋势</h3>
        <div ref="stepChart" class="chart"></div>
      </div>

      <!-- 睡眠质量分析 -->
      <div class="chart-card">
        <h3>睡眠质量分析</h3>
        <div class="sleep-charts">
          <div ref="sleepPieChart" class="chart pie-chart"></div>
          <div ref="sleepBarChart" class="chart bar-chart"></div>
        </div>
      </div>

      <!-- 饮水记录 -->
      <div class="chart-card">
        <h3>饮水记录</h3>
        <div ref="waterChart" class="chart"></div>
      </div>

      <!-- 健康指标雷达图 -->
      <div class="chart-card">
        <h3>健康指标综合评估</h3>
        <div ref="radarChart" class="chart"></div>
      </div>
    </div>

    <!-- 详细数据部分 -->
    <div class="health-details">
      <!-- 睡眠数据 -->
      <div class="detail-section">
        <h2 class="section-title">睡眠分析</h2>
        <div class="detail-grid">
          <div class="detail-item">
            <label>入睡时间</label>
            <p>{{ formatTime(reportData.sleepTime) || '--' }}</p>
          </div>
          <div class="detail-item">
            <label>起床时间</label>
            <p>{{ formatTime(reportData.wakeupTime) || '--' }}</p>
          </div>
          <div class="detail-item">
            <label>深度睡眠</label>
            <p>{{ reportData.deepSleepPercentage || '--' }}%</p>
          </div>
          <div class="detail-item">
            <label>浅度睡眠</label>
            <p>{{ reportData.lightSleepPercentage || '--' }}%</p>
          </div>
          <div class="detail-item">
            <label>REM睡眠</label>
            <p>{{ reportData.remSleepPercentage || '--' }}%</p>
          </div>
        </div>
      </div>

      <!-- 健康指标 -->
      <div class="detail-section">
        <h2 class="section-title">健康指标</h2>
        <div class="detail-grid">
          <div class="detail-item">
            <label>收缩压</label>
            <p>{{ reportData.sbp || '--' }} mmHg</p>
          </div>
          <div class="detail-item">
            <label>舒张压</label>
            <p>{{ reportData.dbp || '--' }} mmHg</p>
          </div>
          <div class="detail-item">
            <label>体重</label>
            <p>{{ reportData.weightDiff || '--' }} kg</p>
          </div>
          <div class="detail-item">
            <label>运动时长</label>
            <p>{{ reportData.sportTimeLong || '--' }} 小时</p>
          </div>
        </div>
      </div>

      <!-- 健康建议 -->
      <div class="detail-section" v-if="suggestions && suggestions.length > 0">
        <h2 class="section-title">健康建议</h2>
        <div class="suggestions-grid">
          <div v-for="(suggestion, index) in suggestions" 
               :key="index" 
               class="suggestion-item"
               :class="getSuggestionPriorityClass(suggestion.priority)">
            <div class="suggestion-header">
              <span class="suggestion-category">{{ suggestion.category }}</span>
              <span class="suggestion-title">{{ suggestion.title }}</span>
            </div>
            <p class="suggestion-content">{{ suggestion.content }}</p>
          </div>
        </div>
      </div>

      <!-- 其他数据 -->
      <div class="detail-section">
        <h2 class="section-title">其他信息</h2>
        <div class="detail-grid">
          <div class="detail-item">
            <label>连续记录天数</label>
            <p>{{ reportData.continuousDays || '--' }} 天</p>
          </div>
          <div class="detail-item">
            <label>记录日期</label>
            <p>{{ formatDate(reportData.createTime) || '--' }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部备注 -->
    <div class="report-footer">
      <p>数据更新时间: {{ formatDateTime(reportData.createTime) }}</p>
      <p class="disclaimer">* 本报告仅供参考，如有健康问题请咨询专业医生</p>
    </div>

    <!-- 返回顶部按钮 -->
    <div class="back-to-top" @click="scrollToTop" v-show="showBackToTop">
      <i class="el-icon-top"></i>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request.js'
import * as echarts from 'echarts'

export default {
  name: 'HealthReport',
  props: {
    headTitle: {
      type: String,
      default: '个人健康报告'
    },
    initialReportData: {
      type: Object,
      default: () => ({
        id: null,
        userId: null,
        stepNumber: null,
        waterVolume: null,
        sleepTime: null,
        wakeupTime: null,
        sbp: null,
        dbp: null,
        weightDiff: null,
        createTime: null,
        continuousDays: null,
        deepSleepPercentage: null,
        lightSleepPercentage: null,
        remSleepPercentage: null
      })
    }
  },
  data() {
    return {
      currentDate: new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      }),
      encrypt: undefined,
      id: undefined,
      reportData: {},
      yesterdayData: {},
      charts: {
        stepChart: null,
        sleepPieChart: null,
        sleepBarChart: null,
        waterChart: null,
        radarChart: null
      },
      showBackToTop: false,
      // 定义统一的颜色方案
      colorPalette: {
        // 步数相关
        step: {
          primary: '#95D3A2',    // 柔和的绿色
          light: '#C8E6C9',      // 浅绿色
          gradient: ['rgba(149, 211, 162, 0.3)', 'rgba(149, 211, 162, 0.1)']
        },
        // 睡眠相关
        sleep: {
          deep: '#8BB4E3',      // 柔和的深蓝色
          light: '#B3D1F0',     // 柔和的浅蓝色
          rem: '#D5E6F7'        // 最浅的蓝色
        },
        // 饮水相关
        water: {
          primary: '#89C4E1',   // 柔和的水蓝色
          light: '#B5DAF0',     // 浅水蓝色
          gradient: ['#89C4E1', '#B5DAF0']
        },
        // 健康指标雷达图
        radar: {
          line: '#9CB4CC',      // 柔和的灰蓝色
          area: ['rgba(156, 180, 204, 0.5)', 'rgba(156, 180, 204, 0.1)']
        }
      },
      suggestions: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
    window.addEventListener('resize', this.handleResize)
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    window.removeEventListener('scroll', this.handleScroll)
    Object.values(this.charts).forEach(chart => {
      chart && chart.dispose()
    })
  },
  created() {
    this.encrypt = this.$route.query.encrypt
    this.id = this.$route.query.id
    if (this.id != null && this.id != undefined) {
      this.ReportShowById(this.id)
      return;
    }
    if (this.encrypt != null && this.encrypt != undefined) {
      this.ReportShow(this.encrypt)
    }
  },
  methods: {
    initCharts() {
      // 确保DOM元素存在
      if (this.$refs.stepChart) {
        this.charts.stepChart = echarts.init(this.$refs.stepChart)
      }
      if (this.$refs.sleepPieChart) {
        this.charts.sleepPieChart = echarts.init(this.$refs.sleepPieChart)
      }
      if (this.$refs.sleepBarChart) {
        this.charts.sleepBarChart = echarts.init(this.$refs.sleepBarChart)
      }
      if (this.$refs.waterChart) {
        this.charts.waterChart = echarts.init(this.$refs.waterChart)
      }
      if (this.$refs.radarChart) {
        this.charts.radarChart = echarts.init(this.$refs.radarChart)
      }

      // 只有当reportData有数据时才更新图表
      if (Object.keys(this.reportData).length > 0) {
        this.updateCharts()
      }
    },
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        chart && chart.resize()
      })
    },
    updateCharts() {
      // 确保图表实例存在再更新
      if (this.charts.stepChart) {
        this.updateStepChart()
      }
      if (this.charts.sleepPieChart && this.charts.sleepBarChart) {
        this.updateSleepCharts()
      }
      if (this.charts.waterChart) {
        this.updateWaterChart()
      }
      if (this.charts.radarChart) {
        this.updateRadarChart()
      }
    },
    updateStepChart() {
      if (!this.reportData || !this.reportData.sleepTime || !this.reportData.wakeupTime) {
        return;
      }

      // 生成24小时的时间点
      const timePoints = [];
      for (let i = 0; i < 24; i++) {
        timePoints.push(`${String(i).padStart(2, '0')}:00`);
      }

      // 从睡醒时间开始统计步数
      const wakeupTime = new Date(this.reportData.wakeupTime);
      const sleepTime = new Date(this.reportData.sleepTime);
      const wakeHour = wakeupTime.getHours();
      const sleepHour = sleepTime.getHours();
      
      // 生成步数数据，考虑活动规律
      const totalSteps = Number(this.reportData.stepNumber) || 0;
      const stepData = new Array(24).fill(0);
      
      // 定义活动时间段权重
      const timeWeights = {
        morning: { start: wakeHour, end: Math.min(wakeHour + 3, sleepHour), weight: 0.3 },
        afternoon: { start: Math.min(wakeHour + 3, sleepHour), end: Math.min(wakeHour + 8, sleepHour), weight: 0.4 },
        evening: { start: Math.min(wakeHour + 8, sleepHour), end: sleepHour, weight: 0.3 }
      };

      // 为每个时间段分配步数并添加随机波动
      Object.values(timeWeights).forEach(period => {
        if (period.start >= period.end) return;
        
        const periodSteps = Math.floor(totalSteps * period.weight);
        const hoursInPeriod = period.end - period.start;
        const baseStepsPerHour = Math.floor(periodSteps / hoursInPeriod);
        
        for (let hour = period.start; hour < period.end; hour++) {
          // 添加±20%的随机波动
          const randomFactor = 0.8 + Math.random() * 0.4;
          stepData[hour] = Math.floor(baseStepsPerHour * randomFactor);
        }
      });

      // 调整总步数以匹配实际值
      const currentTotal = stepData.reduce((a, b) => a + b, 0);
      if (currentTotal > 0) {
        const adjustmentFactor = totalSteps / currentTotal;
        stepData.forEach((value, index) => {
          stepData[index] = Math.floor(value * adjustmentFactor);
        });
      }

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>步数: {c}',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          textStyle: {
            color: '#666'
          }
        },
        xAxis: {
          type: 'category',
          data: timePoints,
          axisLine: {
            lineStyle: {
              color: this.colorPalette.step.primary
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '步数',
          axisLine: {
            lineStyle: {
              color: this.colorPalette.step.primary
            }
          }
        },
        series: [{
          data: stepData,
          type: 'line',
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.colorPalette.step.gradient[0] },
              { offset: 1, color: this.colorPalette.step.gradient[1] }
            ])
          },
          lineStyle: {
            color: this.colorPalette.step.primary,
            width: 3
          },
          itemStyle: {
            color: this.colorPalette.step.primary
          }
        }]
      };

      this.charts.stepChart.setOption(option);
    },
    updateSleepCharts() {
      if (!this.reportData || !this.reportData.sleepTime || !this.reportData.wakeupTime) {
        return;
      }

      // 定义睡眠周期常量
      const CYCLE_LENGTH = 90; // 一个睡眠周期90分钟

      // 计算每种睡眠的实际时长（分钟）
      const totalMinutes = this.reportData.timeSubHour * 60 + this.reportData.timeSubMinutes;
      const deepSleepMinutes = Math.round(totalMinutes * (this.reportData.deepSleepPercentage / 100));
      const lightSleepMinutes = Math.round(totalMinutes * (this.reportData.lightSleepPercentage / 100));
      const remSleepMinutes = Math.round(totalMinutes * (this.reportData.remSleepPercentage / 100));

      // 生成睡眠阶段数据
      const sleepStages = [];
      let currentTime = new Date(this.reportData.sleepTime);
      
      // 定义每个阶段的权重分布（基于睡眠周期规律）
      const getStageWeights = (minutesFromSleep, totalSleepHours) => {
        const cyclePosition = (minutesFromSleep % CYCLE_LENGTH) / CYCLE_LENGTH;
        const hourFromSleep = minutesFromSleep / 60;

        // 计算每小时应该分配的深度睡眠基准比例
        // 确保深度睡眠均匀分布在整个睡眠时间内
        const baseDeepSleepRatio = deepSleepMinutes / (totalMinutes * 0.9); // 预留10%的调整空间
        
        // 根据睡眠周期调整深度睡眠比例
        let deepSleepRatio = baseDeepSleepRatio;
        let remRatio = 0.25;
        let lightRatio = 1 - deepSleepRatio - remRatio;

        // 最后一小时稍微减少深度睡眠
        if (hourFromSleep >= totalSleepHours - 1) {
          deepSleepRatio *= 0.7;
          remRatio = 0.4;
          lightRatio = 1 - deepSleepRatio - remRatio;
        }

        // 根据睡眠周期位置微调比例
        if (cyclePosition < 0.3) {
          // 周期开始时增加深度睡眠
          return {
            deep: Math.min(0.7, deepSleepRatio * 1.2),
            rem: Math.max(0.1, remRatio * 0.8),
            light: Math.max(0.2, 1 - (deepSleepRatio * 1.2) - (remRatio * 0.8))
          };
        } else if (cyclePosition < 0.6) {
          // 周期中间保持基准比例
          return {
            deep: deepSleepRatio,
            rem: remRatio,
            light: lightRatio
          };
        } else {
          // 周期末尾略微减少深度睡眠
          return {
            deep: Math.max(0.2, deepSleepRatio * 0.9),
            rem: Math.min(0.4, remRatio * 1.2),
            light: Math.max(0.2, 1 - (deepSleepRatio * 0.9) - (remRatio * 1.2))
          };
        }
      };

      // 计算总睡眠小时数用于权重计算
      const totalSleepHours = totalMinutes / 60;

      // 跟踪已分配的时间
      let allocatedDeep = 0;
      let allocatedLight = 0;
      let allocatedRem = 0;

      // 预先计算每小时的目标深度睡眠分配量
      const targetDeepSleepPerHour = deepSleepMinutes / totalSleepHours;

      // 生成每小时的睡眠阶段数据
      while (currentTime < new Date(this.reportData.wakeupTime)) {
        const hour = currentTime.getHours();
        const timeLabel = `${String(hour).padStart(2, '0')}:00`;
        
        // 计算当前小时段的实际分钟数
        let availableMinutes = 60;
        
        // 处理入睡时间所在的小时
        if (currentTime.getHours() === new Date(this.reportData.sleepTime).getHours() && 
            currentTime.getDate() === new Date(this.reportData.sleepTime).getDate()) {
          availableMinutes = 60 - new Date(this.reportData.sleepTime).getMinutes();
        }
        
        // 处理起床时间所在的小时
        if (currentTime.getHours() === new Date(this.reportData.wakeupTime).getHours() && 
            currentTime.getDate() === new Date(this.reportData.wakeupTime).getDate()) {
          availableMinutes = new Date(this.reportData.wakeupTime).getMinutes();
        }
        
        // 计算从入睡开始的分钟数
        const minutesFromSleep = (currentTime - new Date(this.reportData.sleepTime)) / (1000 * 60);
        
        // 获取基础权重
        const weights = getStageWeights(minutesFromSleep, totalSleepHours);
        
        // 计算当前小时还需要分配的总分钟数
        const remainingDeep = deepSleepMinutes - allocatedDeep;
        const remainingLight = lightSleepMinutes - allocatedLight;
        const remainingRem = remSleepMinutes - allocatedRem;

        // 计算当前小时的目标深度睡眠时间
        const targetDeepSleep = Math.min(
          Math.round(targetDeepSleepPerHour * (availableMinutes / 60)),
          remainingDeep
        );

        // 分配深度睡眠
        let deep = Math.max(
          Math.min(targetDeepSleep, availableMinutes * 0.7),
          Math.round(availableMinutes * weights.deep)
        );

        // 确保不超过剩余配额
        deep = Math.min(deep, remainingDeep);

        // 分配剩余时间给浅睡眠和REM
        const remainingMinutes = availableMinutes - deep;
        const remWeight = weights.rem / (weights.rem + weights.light);
        let rem = Math.min(
          Math.round(remainingMinutes * remWeight),
          remainingRem
        );
        let light = Math.min(
          remainingMinutes - rem,
          remainingLight
        );

        // 确保总和不超过当前可用分钟数
        const total = deep + light + rem;
        if (total > availableMinutes) {
          const scale = availableMinutes / total;
          deep = Math.round(deep * scale);
          light = Math.round(light * scale);
          rem = Math.round(rem * scale);
        }

        // 更新已分配时间
        allocatedDeep += deep;
        allocatedLight += light;
        allocatedRem += rem;

        sleepStages.push({
          time: timeLabel,
          deep,
          light,
          rem,
          total: deep + light + rem
        });

        // 移动到下一个小时
        currentTime = new Date(currentTime.setHours(currentTime.getHours() + 1, 0, 0, 0));
      }

      // 处理最后一个小时的剩余时间分配
      if (allocatedDeep < deepSleepMinutes || allocatedLight < lightSleepMinutes || allocatedRem < remSleepMinutes) {
        const lastStage = sleepStages[sleepStages.length - 1];
        const remainingMinutes = Math.min(
          60 - lastStage.total,
          deepSleepMinutes - allocatedDeep + lightSleepMinutes - allocatedLight + remSleepMinutes - allocatedRem
        );

        if (remainingMinutes > 0) {
          const remainingDeep = deepSleepMinutes - allocatedDeep;
          const remainingLight = lightSleepMinutes - allocatedLight;
          const remainingRem = remSleepMinutes - allocatedRem;

          const total = remainingDeep + remainingLight + remainingRem;
          const scale = remainingMinutes / total;

          lastStage.deep += Math.round(remainingDeep * scale);
          lastStage.light += Math.round(remainingLight * scale);
          lastStage.rem += Math.round(remainingRem * scale);
          lastStage.total = lastStage.deep + lastStage.light + lastStage.rem;
        }
      }

      // 饼图配置
      const pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}%'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          left: 'center',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '40%'],
          avoidLabelOverlap: true,
          data: [
            { 
              value: this.reportData.deepSleepPercentage || 0, 
              name: '深度睡眠',
              itemStyle: { color: this.colorPalette.sleep.deep }
            },
            { 
              value: this.reportData.lightSleepPercentage || 0, 
              name: '浅度睡眠',
              itemStyle: { color: this.colorPalette.sleep.light }
            },
            { 
              value: this.reportData.remSleepPercentage || 0, 
              name: 'REM睡眠',
              itemStyle: { color: this.colorPalette.sleep.rem }
            }
          ],
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {c}%',
            fontSize: 12,
            color: '#666'
          }
        }]
      };

      // 柱状图配置
      const barOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let result = `${params[0].name}<br/>`;
            params.forEach(param => {
              if (param.value > 0) {
                result += `${param.seriesName}: ${param.value}分钟<br/>`;
              }
            });
            return result;
          }
        },
        legend: {
          data: ['深度睡眠', '浅度睡眠', 'REM睡眠'],
          bottom: 0,
          left: 'center',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: sleepStages.map(stage => stage.time),
          axisLabel: {
            fontSize: 10,
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          name: '分钟',
          max: 60,
          axisLabel: {
            fontSize: 10,
            color: '#666'
          }
        },
        series: [
          {
            name: '深度睡眠',
            type: 'bar',
            stack: 'sleep',
            data: sleepStages.map(stage => stage.deep),
            itemStyle: { color: this.colorPalette.sleep.deep }
          },
          {
            name: '浅度睡眠',
            type: 'bar',
            stack: 'sleep',
            data: sleepStages.map(stage => stage.light),
            itemStyle: { color: this.colorPalette.sleep.light }
          },
          {
            name: 'REM睡眠',
            type: 'bar',
            stack: 'sleep',
            data: sleepStages.map(stage => stage.rem),
            itemStyle: { color: this.colorPalette.sleep.rem }
          }
        ]
      };

      // 确保先设置饼图配置
      if (this.charts.sleepPieChart) {
        this.charts.sleepPieChart.setOption(pieOption);
      }
      // 然后设置柱状图配置
      if (this.charts.sleepBarChart) {
        this.charts.sleepBarChart.setOption(barOption);
      }
    },
    updateWaterChart() {
      if (!this.reportData || !this.reportData.sleepTime || !this.reportData.wakeupTime) {
        return;
      }

      const wakeupTime = new Date(this.reportData.wakeupTime);
      const sleepTime = new Date(this.reportData.sleepTime);
      const wakeHour = wakeupTime.getHours();
      const sleepHour = sleepTime.getHours();

      // 定义饮水高峰时段
      const waterPeaks = [
        { start: wakeHour, end: wakeHour + 2, weight: 0.2 },  // 早晨
        { start: 11, end: 13, weight: 0.3 },  // 午餐
        { start: 14, end: 16, weight: 0.2 },  // 下午
        { start: 17, end: 19, weight: 0.3 }   // 晚餐
      ];

      const totalWater = Number(this.reportData.waterVolume) * 1000; // 转换为毫升
      const waterData = new Array(24).fill(0);

      // 为每个时间段分配饮水量并添加随机波动
      waterPeaks.forEach(peak => {
        if (peak.start >= peak.end) return;
        
        const periodWater = totalWater * peak.weight;
        const hoursInPeriod = peak.end - peak.start;
        const baseWaterPerHour = periodWater / hoursInPeriod;

        for (let hour = peak.start; hour < peak.end; hour++) {
          if (hour >= wakeHour && hour < sleepHour) {
            // 添加±30%的随机波动
            const randomFactor = 0.7 + Math.random() * 0.6;
            waterData[hour] = Math.round(baseWaterPerHour * randomFactor);
          }
        }
      });

      // 调整总量以匹配实际值
      const currentTotal = waterData.reduce((a, b) => a + b, 0);
      if (currentTotal > 0) {
        const adjustmentFactor = totalWater / currentTotal;
        waterData.forEach((value, index) => {
          waterData[index] = Math.round(value * adjustmentFactor);
        });
      }

      const timePoints = Array.from({length: 24}, (_, i) => `${String(i).padStart(2, '0')}:00`);

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>饮水量: {c}ml',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          textStyle: {
            color: '#666'
          }
        },
        xAxis: {
          type: 'category',
          data: timePoints,
          axisLine: {
            lineStyle: {
              color: this.colorPalette.water.primary
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '饮水量(ml)',
          axisLine: {
            lineStyle: {
              color: this.colorPalette.water.primary
            }
          }
        },
        series: [{
          data: waterData,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.colorPalette.water.gradient[0] },
              { offset: 1, color: this.colorPalette.water.gradient[1] }
            ])
          }
        }]
      };

      this.charts.waterChart.setOption(option);
    },
    updateRadarChart() {
      // 获取最大步数（根据实际情况调整）
      const maxSteps = 20000;
      // 获取最大睡眠时间（小时）
      const maxSleepHours = 12;
      // 获取最大饮水量（升）
      const maxWaterVolume = 4;
      // 获取最大血压值
      const maxBloodPressure = 200;
      // 获取最大体重
      const maxWeight = 200;

      const option = {
        radar: {
          indicator: [
            { name: '步数(步)', max: maxSteps },
            { name: '睡眠(小时)', max: maxSleepHours },
            { name: '饮水(L)', max: maxWaterVolume },
            { name: '血压(mmHg)', max: maxBloodPressure },
            { name: '体重(kg)', max: maxWeight }
          ],
          axisLine: {
            lineStyle: {
              color: this.colorPalette.radar.line
            }
          },
          splitLine: {
            lineStyle: {
              color: ['rgba(156, 180, 204, 0.2)']
            }
          }
        },
        series: [{
          type: 'radar',
          data: [{
            value: [
              Math.min(Number(this.reportData.stepNumber) || 0, maxSteps),
              Math.min(this.calculateSleepHours() || 0, maxSleepHours),
              Math.min(Number(this.reportData.waterVolume) || 0, maxWaterVolume),
              Math.min(this.parseBloodPressure() || 0, maxBloodPressure),
              Math.min(Number(this.reportData.weightDiff) || 0, maxWeight)
            ],
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: this.colorPalette.radar.area[0] },
                { offset: 1, color: this.colorPalette.radar.area[1] }
              ])
            },
            lineStyle: {
              color: this.colorPalette.radar.line,
              width: 2
            },
            itemStyle: {
              color: this.colorPalette.radar.line
            }
          }]
        }]
      }
      this.charts.radarChart.setOption(option)
    },
    calculateSleepDuration() {
      if (!this.reportData.timeSubHour && !this.reportData.timeSubMinutes) return '--'
      return `${this.reportData.timeSubHour}小时${this.reportData.timeSubMinutes >= 10 ? this.reportData.timeSubMinutes : `0${this.reportData.timeSubMinutes}`}分钟`
    },
    calculateSleepHours() {
      if (!this.reportData.timeSubHour && !this.reportData.timeSubMinutes) return 0;
      return this.reportData.timeSubHour + (this.reportData.timeSubMinutes / 60);
    },
    parseBloodPressure() {
      if (!this.reportData.sbp) return 0;
      return parseInt(this.reportData.sbp) || 0;
    },
    formatTime(dateString) {
      if (!dateString) return '--';
      const date = new Date(dateString);
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    formatDate(date) {
      if (!date) return '--';
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },
    formatReportDate(date) {
      if (!date) return '';
      const reportDate = new Date(date);
      return reportDate.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      });
    },
    formatDateTime(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    ReportShow(encrypt) {
      request({
        url: `report/decryptDay`,
        method: "get",
        params: {
          encrypt
        }
      }).then(res => {
        if (res.data) {
          // 确保日期字段是有效的
          const todayData = res.data.today;
          const yesterdayData = res.data.yesterday;

          // 处理日期字段
          if (todayData) {
            this.reportData = {
              ...todayData,
              sleepTime: todayData.sleepTime ? new Date(todayData.sleepTime) : null,
              wakeupTime: todayData.wakeupTime ? new Date(todayData.wakeupTime) : null,
              createTime: todayData.createTime ? new Date(todayData.createTime) : null
            };
          }

          if (yesterdayData) {
            this.yesterdayData = {
              ...yesterdayData,
              sleepTime: yesterdayData.sleepTime ? new Date(yesterdayData.sleepTime) : null,
              wakeupTime: yesterdayData.wakeupTime ? new Date(yesterdayData.wakeupTime) : null,
              createTime: yesterdayData.createTime ? new Date(yesterdayData.createTime) : null
            };
          }

          // 更新健康建议
          this.suggestions = res.data.suggestion || [];

          this.$nextTick(() => {
            this.initCharts();
          });
        }
      });
    },
    ReportShowById(id) {
      request({
        url: `report/userReport/Day/${id}`,
        method: "get",
      }).then(res => {
        if (res.data) {
          // 确保日期字段是有效的
          const todayData = res.data.today;
          const yesterdayData = res.data.yesterday;

          // 处理日期字段
          if (todayData) {
            this.reportData = {
              ...todayData,
              sleepTime: todayData.sleepTime ? new Date(todayData.sleepTime) : null,
              wakeupTime: todayData.wakeupTime ? new Date(todayData.wakeupTime) : null,
              createTime: todayData.createTime ? new Date(todayData.createTime) : null
            };
          }

          if (yesterdayData) {
            this.yesterdayData = {
              ...yesterdayData,
              sleepTime: yesterdayData.sleepTime ? new Date(yesterdayData.sleepTime) : null,
              wakeupTime: yesterdayData.wakeupTime ? new Date(yesterdayData.wakeupTime) : null,
              createTime: yesterdayData.createTime ? new Date(yesterdayData.createTime) : null
            };
          }

          // 更新健康建议
          this.suggestions = res.data.suggestion || [];

          this.$nextTick(() => {
            this.initCharts();
          });
        }
      });
    },
    getStepTrendClass() {
      if (!this.reportData.stepNumber || !this.yesterdayData) return ''
      return Number(this.reportData.stepNumber) >= Number(this.yesterdayData.stepNumber || 0) ? 'trend-up' : 'trend-down'
    },
    getWaterTrendClass() {
      if (!this.reportData.waterVolume || !this.yesterdayData) return ''
      return Number(this.reportData.waterVolume) >= Number(this.yesterdayData.waterVolume || 0) ? 'trend-up' : 'trend-down'
    },
    getSleepTrendClass() {
      if (!this.reportData.timeSubHour || !this.yesterdayData) return ''
      const todayMinutes = this.reportData.timeSubHour * 60 + this.reportData.timeSubMinutes
      const yesterdayMinutes = this.yesterdayData ? 
        (this.yesterdayData.timeSubHour * 60 + this.yesterdayData.timeSubMinutes) : 0
      return todayMinutes >= yesterdayMinutes ? 'trend-up' : 'trend-down'
    },
    getStepTrendText() {
      if (!this.reportData.stepNumber || !this.yesterdayData) return '-- 步'
      const diff = Number(this.reportData.stepNumber) - Number(this.yesterdayData.stepNumber || 0)
      const symbol = diff >= 0 ? '↑' : '↓'
      return `${symbol} 较昨日 ${Math.abs(diff)}步`
    },
    getWaterTrendText() {
      if (!this.reportData.waterVolume || !this.yesterdayData) return '-- L'
      const diff = (Number(this.reportData.waterVolume) - Number(this.yesterdayData.waterVolume || 0)).toFixed(2)
      const symbol = diff >= 0 ? '↑' : '↓'
      return `${symbol} 较昨日 ${Math.abs(diff)}L`
    },
    getSleepTrendText() {
      if (!this.reportData.timeSubHour || !this.yesterdayData) return '--'
      const todayMinutes = this.reportData.timeSubHour * 60 + this.reportData.timeSubMinutes
      const yesterdayMinutes = this.yesterdayData ? 
        (this.yesterdayData.timeSubHour * 60 + this.yesterdayData.timeSubMinutes) : 0
      const diffMinutes = todayMinutes - yesterdayMinutes
      const hours = Math.floor(Math.abs(diffMinutes) / 60)
      const minutes = Math.abs(diffMinutes) % 60
      const symbol = diffMinutes >= 0 ? '↑' : '↓'
      let text = `${symbol} 较昨日 `
      if (hours > 0) {
        text += `${hours}小时`
      }
      if (minutes > 0) {
        text += `${minutes}分钟`
      }
      return text || '持平'
    },
    handleScroll() {
      this.showBackToTop = window.scrollY > 300
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    getSuggestionPriorityClass(priority) {
      switch (priority) {
        case 'high':
          return 'priority-high';
        case 'medium':
          return 'priority-medium';
        case 'low':
          return 'priority-low';
        default:
          return '';
      }
    }
  }
}
</script>

<style scoped>
.health-report-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
  color: #333;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.report-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.report-header h1 {
  color: #2c3e50;
  margin-bottom: 5px;
}

.report-date {
  color: #7f8c8d;
  font-size: 16px;
}

.health-summary {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.summary-card {
  flex: 1;
  min-width: 200px;
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin: 0 5px 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
}

.summary-icon {
  font-size: 24px;
  margin-right: 15px;
}

.summary-content {
  flex: 1;
}

.summary-content h3 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #7f8c8d;
}

.summary-value {
  margin: 0 0 5px 0;
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.trend-indicator {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.trend-up {
  color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
}

.trend-down {
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.chart-card h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
}

.chart {
  height: 300px;
}

.sleep-charts {
  display: flex;
  gap: 20px;
}

.pie-chart {
  flex: 1;
  height: 250px;
}

.bar-chart {
  flex: 2;
  height: 250px;
}

.health-details {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  color: #3498db;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  margin-bottom: 15px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.detail-item {
  background: #f8fafc;
  padding: 12px;
  border-radius: 6px;
}

.detail-item label {
  display: block;
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.detail-item p {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.report-footer {
  text-align: center;
  color: #7f8c8d;
  font-size: 12px;
}

.disclaimer {
  font-style: italic;
  margin-top: 5px;
}

.back-button {
  position: fixed;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  z-index: 100;
}

.back-button:hover {
  background-color: #f5f7fa;
  transform: translateX(-5px);
}

.back-button i {
  margin-right: 5px;
  font-size: 16px;
}

.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  z-index: 100;
}

.back-to-top:hover {
  background-color: #f5f7fa;
  transform: translateY(-5px);
}

.back-to-top i {
  font-size: 20px;
  color: #409EFF;
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }

  .health-summary {
    flex-direction: column;
  }

  .summary-card {
    margin-bottom: 10px;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }

  .back-button {
    top: 10px;
    right: 10px;
    padding: 6px 12px;
  }

  .back-to-top {
    bottom: 10px;
    right: 10px;
    width: 36px;
    height: 36px;
  }
}

.suggestions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.suggestion-item {
  background: #f8fafc;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
  transition: all 0.3s ease;
}

.suggestion-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.suggestion-item.priority-high {
  border-left-color: #F56C6C;
}

.suggestion-item.priority-medium {
  border-left-color: #E6A23C;
}

.suggestion-item.priority-low {
  border-left-color: #67C23A;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.suggestion-category {
  font-size: 14px;
  color: #909399;
  background: rgba(144, 147, 153, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
}

.suggestion-title {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.suggestion-content {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}
</style>